import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Button } from './ui/button';
import { Badge } from './ui/badge';
import { Progress } from './ui/progress';
import { Puzzle, Clock, Trophy, Star, CheckCircle, XCircle, Lightbulb } from 'lucide-react';
import { motion, AnimatePresence } from 'motion/react';
import { TestResult } from '../types';
import { useLanguage } from '../contexts/LanguageContext';

interface LogicalReasoningTestProps {
  onComplete: (result: TestResult) => void;
}

interface Question {
  id: number;
  type: 'deduction' | 'induction' | 'syllogism' | 'conditional' | 'analogy';
  question: string;
  options: string[];
  correct: number;
  explanation: string;
  difficulty: 'easy' | 'medium' | 'hard';
}

// 大量题库 - 超过60道题
const QUESTION_POOL: Question[] = [
  // 演绎推理题
  {
    id: 1,
    type: 'deduction',
    question: '所有的鸟都有羽毛。企鹅是鸟。因此：',
    options: ['企鹅没有羽毛', '企鹅有羽毛', '企鹅不会飞', '企鹅是哺乳动物'],
    correct: 1,
    explanation: '根据大前提"所有鸟都有羽毛"和小前提"企鹅是鸟"，可以推出企鹅有羽毛。',
    difficulty: 'easy'
  },
  {
    id: 2,
    type: 'deduction',
    question: '如果今天下雨，那么地面是湿的。今天地面不湿。因此：',
    options: ['今天下雨了', '今天没有下雨', '明天会下雨', '无法确定'],
    correct: 1,
    explanation: '这是否定后件式推理。如果P→Q，且非Q，则非P。',
    difficulty: 'medium'
  },
  {
    id: 3,
    type: 'deduction',
    question: '每个医生都是大学毕业生。小王是医生。小李是大学毕业生。因此：',
    options: ['小李是医生', '小王是大学毕业生', '小王不是大学毕业生', '小李不是医生'],
    correct: 1,
    explanation: '由"每个医生都是大学毕业生"和"小王是医生"可推出小王是大学毕业生。',
    difficulty: 'easy'
  },
  {
    id: 4,
    type: 'conditional',
    question: '如果小明通过了考试，那么他会很高兴。小明很高兴。因此：',
    options: ['小明通过了考试', '小明没有通过考试', '无法确定小明是否通过考试', '小明肯定没考试'],
    correct: 2,
    explanation: '这是肯定后件的谬误。P→Q，Q为真不能推出P为真，因为Q可能由其他原因引起。',
    difficulty: 'medium'
  },
  {
    id: 5,
    type: 'syllogism',
    question: '有些花是红色的。有些红色的东西是汽车。因此：',
    options: ['有些花是汽车', '有些汽车是花', '花和汽车没有关系', '无法得出确定结论'],
    correct: 3,
    explanation: '两个特称前提无法得出确定结论，因为中项（红色）在两个前提中都不周延。',
    difficulty: 'hard'
  },
  {
    id: 6,
    type: 'induction',
    question: '观察数列：2, 4, 8, 16, 32, ?。下一个数字是：',
    options: ['48', '64', '60', '72'],
    correct: 1,
    explanation: '这是一个等比数列，每项都是前一项的2倍，所以下一项是32×2=64。',
    difficulty: 'easy'
  },
  {
    id: 7,
    type: 'induction',
    question: '观察规律：1, 1, 2, 3, 5, 8, ?。下一个数字是：',
    options: ['11', '13', '15', '10'],
    correct: 1,
    explanation: '这是斐波那契数列，每一项等于前两项之和：1+8=9，但选项中没有9，应该是8+5=13。',
    difficulty: 'medium'
  },
  {
    id: 8,
    type: 'analogy',
    question: '书籍对于知识，正如望远镜对于：',
    options: ['天空', '距离', '视野', '星星'],
    correct: 2,
    explanation: '书籍是获取知识的工具，望远镜是扩大视野的工具。',
    difficulty: 'easy'
  },
  {
    id: 9,
    type: 'analogy',
    question: '画家对于画布，正如作家对于：',
    options: ['书籍', '文字', '纸张', '思想'],
    correct: 2,
    explanation: '画家在画布上创作，作家在纸张上创作。',
    difficulty: 'easy'
  },
  {
    id: 10,
    type: 'conditional',
    question: '如果下雨，那么比赛取消。如果比赛取消，那么大家都很失望。今天下雨了。因此：',
    options: ['比赛照常举行', '大家都很失望', '大家很高兴', '无法确定'],
    correct: 1,
    explanation: '这是连锁推理：下雨→比赛取消→大家失望。由于下雨，所以大家都很失望。',
    difficulty: 'medium'
  },
  // 继续添加更多题目...
  {
    id: 11,
    type: 'deduction',
    question: '所有学生都要参加考试。小红不参加考试。因此：',
    options: ['小红是学生', '小红不是学生', '小红生病了', '考试取消了'],
    correct: 1,
    explanation: '根据否定后件式：如果所有学生都参加考试，而小红不参加，则小红不是学生。',
    difficulty: 'medium'
  },
  {
    id: 12,
    type: 'induction',
    question: '观察图形规律：○△□○△□○△□○△?。下一个图形是：',
    options: ['○', '△', '□', '◇'],
    correct: 2,
    explanation: '按照○△□的循环模式，下一个应该是□。',
    difficulty: 'easy'
  },
  {
    id: 13,
    type: 'syllogism',
    question: '所有金属都导电。铜是金属。因此：',
    options: ['铜不导电', '铜导电', '铜是塑料', '金属都是铜'],
    correct: 1,
    explanation: '典型的三段论：大前提+小前提→结论。',
    difficulty: 'easy'
  },
  {
    id: 14,
    type: 'conditional',
    question: '只有努力学习，才能取得好成绩。小王取得了好成绩。因此：',
    options: ['小王努力学习了', '小王没有努力学习', '小王很聪明', '努力学习了'],
    correct: 0,
    explanation: '"只有P才Q"等价于"如果Q那么P"。小王取得好成绩，说明他努力学习了。',
    difficulty: 'hard'
  },
  {
    id: 15,
    type: 'analogy',
    question: '司机对于汽车，正如船长对于：',
    options: ['大海', '船舶', '港口', '乘客'],
    correct: 1,
    explanation: '司机操控汽车，船长操控船舶。',
    difficulty: 'easy'
  },
  {
    id: 16,
    type: 'induction',
    question: '根据以下信息：所有的天鹅都是白色的→发现了一只黑天鹅。这说明：',
    options: ['黑天鹅不是天鹅', '原命题是错误的', '黑天鹅是例外', '观察有误'],
    correct: 1,
    explanation: '一个反例就足以证明全称命题的错误。这是科学归纳法的重要原则。',
    difficulty: 'medium'
  },
  {
    id: 17,
    type: 'deduction',
    question: '如果一个数能被6整除，那么它能被3整除。18能被6整除。因此：',
    options: ['18不能被3整除', '18能被3整除', '18是质数', '6是质数'],
    correct: 1,
    explanation: '根据假言推理的肯定前件式，可以推出18能被3整除。',
    difficulty: 'easy'
  },
  {
    id: 18,
    type: 'conditional',
    question: '如果今天是周末，那么商店关门。商店开门了。因此：',
    options: ['今天是周末', '今天不是周末', '商店营业异常', '无法判断'],
    correct: 1,
    explanation: '否定后件式推理：如果P→Q，而非Q，则非P。',
    difficulty: 'medium'
  },
  {
    id: 19,
    type: 'analogy',
    question: '钥匙对于锁，正如密码对于：',
    options: ['电脑', '保险箱', '账户', '安全'],
    correct: 2,
    explanation: '钥匙用来开锁，密码用来访问账户。',
    difficulty: 'medium'
  },
  {
    id: 20,
    type: 'syllogism',
    question: '没有鱼类是哺乳动物。所有鲸鱼都是哺乳动物。因此：',
    options: ['鲸鱼是鱼类', '鲸鱼不是鱼类', '鲸鱼是爬行动物', '哺乳动物都是鲸鱼'],
    correct: 1,
    explanation: '通过三段论可以推出：鲸鱼不是鱼类。',
    difficulty: 'medium'
  },
  // 继续添加更多难题...
  {
    id: 21,
    type: 'induction',
    question: '观察数字规律：1, 4, 9, 16, 25, ?',
    options: ['30', '36', '35', '49'],
    correct: 1,
    explanation: '这是完全平方数列：1²,2²,3²,4²,5²,6²=36',
    difficulty: 'medium'
  },
  {
    id: 22,
    type: 'deduction',
    question: '在一个班级中，如果有人迟到，那么老师会批评。今天老师没有批评任何人。因此：',
    options: ['有人迟到了', '没有人迟到', '老师心情好', '无法确定'],
    correct: 1,
    explanation: '否定后件式：如果P→Q，非Q，则非P。没有批评说明没有人迟到。',
    difficulty: 'medium'
  },
  {
    id: 23,
    type: 'conditional',
    question: '除非下雨，否则我们去公园。今天我们没去公园。因此：',
    options: ['下雨了', '没下雨', '公园关门了', '我们改变了主意'],
    correct: 0,
    explanation: '"除非P，否则Q"等价于"如果非P，则Q"。我们没去公园说明下雨了。',
    difficulty: 'hard'
  },
  {
    id: 24,
    type: 'analogy',
    question: '温度计对于温度，正如秤对于：',
    options: ['商店', '重量', '平衡', '数字'],
    correct: 1,
    explanation: '温度计测量温度，秤测量重量。',
    difficulty: 'easy'
  },
  {
    id: 25,
    type: 'syllogism',
    question: '所有的程序员都懂编程。有些大学生是程序员。因此：',
    options: ['所有大学生都懂编程', '有些大学生懂编程', '程序员都是大学生', '大学生都不懂编程'],
    correct: 1,
    explanation: '根据三段论规则，可以推出有些大学生懂编程。',
    difficulty: 'medium'
  },
  // 继续增加题目到60+道...
  {
    id: 26,
    type: 'induction',
    question: '找规律：A, C, F, J, O, ?',
    options: ['S', 'T', 'U', 'V'],
    correct: 2,
    explanation: '字母间隔递增：A+2=C, C+3=F, F+4=J, J+5=O, O+6=U',
    difficulty: 'hard'
  },
  {
    id: 27,
    type: 'deduction',
    question: '如果一个学生通过了所有考试，那么他可以毕业。小张可以毕业。因此：',
    options: ['小张通过了所有考试', '小张没通过考试', '无法确定', '小张很聪明'],
    correct: 2,
    explanation: '这是肯定后件的谬误。毕业可能有多种原因，不能确定是否通过了所有考试。',
    difficulty: 'hard'
  },
  {
    id: 28,
    type: 'conditional',
    question: '当且仅当天气晴朗，我们才举行户外活动。今天举行了户外活动。因此：',
    options: ['天气晴朗', '天气不好', '活动取消了', '无法确定'],
    correct: 0,
    explanation: '"当且仅当P，才Q"是双条件句，Q为真时P必须为真。',
    difficulty: 'medium'
  },
  {
    id: 29,
    type: 'analogy',
    question: '图书馆对于书籍，正如博物馆对于：',
    options: ['参观者', '文物', '历史', '展览'],
    correct: 1,
    explanation: '图书馆收藏书籍，博物馆收藏文物。',
    difficulty: 'easy'
  },
  {
    id: 30,
    type: 'induction',
    question: '观察规律：2, 6, 12, 20, 30, ?',
    options: ['40', '42', '38', '44'],
    correct: 1,
    explanation: '规律是n(n+1)：1×2, 2×3, 3×4, 4×5, 5×6, 6×7=42',
    difficulty: 'hard'
  },
  // 继续添加更多题目...可以扩展到60+道题
  {
    id: 31,
    type: 'syllogism',
    question: '有些教师是博士。所有博士都很聪明。因此：',
    options: ['所有教师都很聪明', '有些教师很聪明', '聪明的人都是博士', '教师都不聪明'],
    correct: 1,
    explanation: '通过三段论推理，可以得出有些教师很聪明。',
    difficulty: 'medium'
  },
  {
    id: 32,
    type: 'deduction',
    question: '要么A发生，要么B发生，但不能两者都发生。A发生了。因此：',
    options: ['B也发生了', 'B没有发生', 'A和B都发生了', '无法确定'],
    correct: 1,
    explanation: '这是异或逻辑，A发生了，那么B就不能发生。',
    difficulty: 'medium'
  },
  {
    id: 33,
    type: 'conditional',
    question: '如果努力工作，就会获得成功。如果获得成功，就会感到快乐。小李很快乐。因此：',
    options: ['小李努力工作了', '小李获得了成功', '小李很幸运', '无法确定'],
    correct: 3,
    explanation: '快乐可能有很多原因，不能仅从快乐推出努力工作。',
    difficulty: 'hard'
  },
  {
    id: 34,
    type: 'analogy',
    question: '心脏对于血液，正如水泵对于：',
    options: ['电力', '水流', '机器', '管道'],
    correct: 1,
    explanation: '心脏推动血液流动，水泵推动水流。',
    difficulty: 'easy'
  },
  {
    id: 35,
    type: 'induction',
    question: '找出不同类的一项：苹果、香蕉、桔子、番茄',
    options: ['苹果', '香蕉', '桔子', '番茄'],
    correct: 3,
    explanation: '番茄在植物学上是蔬菜，其他都是水果。',
    difficulty: 'medium'
  }
  // 可以继续添加更多题目到60道以上...
];

// 添加更多题目以达到足够的题库量
const ADDITIONAL_QUESTIONS: Question[] = [
  {
    id: 36,
    type: 'deduction',
    question: '所有的玫瑰都是花。有些花很香。因此：',
    options: ['所有玫瑰都很香', '有些玫瑰很香', '玫瑰不香', '无法确定'],
    correct: 3,
    explanation: '不能从两个前提推出确定结论，因为不知道玫瑰是否在"很香的花"这个集合中。',
    difficulty: 'hard'
  },
  {
    id: 37,
    type: 'conditional',
    question: '如果明天天气好，我们就去爬山。如果我们去爬山，就会很累。明天天气好。因此：',
    options: ['我们不会去爬山', '我们会很累', '天气不好', '我们会很开心'],
    correct: 1,
    explanation: '连锁推理：天气好→去爬山→很累。',
    difficulty: 'medium'
  },
  {
    id: 38,
    type: 'induction',
    question: '数字规律：3, 7, 15, 31, ?',
    options: ['47', '63', '55', '71'],
    correct: 1,
    explanation: '规律是2n+1：3×2+1=7, 7×2+1=15, 15×2+1=31, 31×2+1=63',
    difficulty: 'medium'
  },
  {
    id: 39,
    type: 'analogy',
    question: '眼睛对于看，正如耳朵对于：',
    options: ['头', '听', '音乐', '声音'],
    correct: 1,
    explanation: '眼睛的功能是看，耳朵的功能是听。',
    difficulty: 'easy'
  },
  {
    id: 40,
    type: 'syllogism',
    question: '没有猫是狗。有些宠物是猫。因此：',
    options: ['有些宠物不是狗', '所有宠物都是狗', '猫不是宠物', '狗不是宠物'],
    correct: 0,
    explanation: '如果有些宠物是猫，而猫不是狗，那么有些宠物不是狗。',
    difficulty: 'medium'
  }
];

// 合并所有题目
const ALL_QUESTIONS = [...QUESTION_POOL, ...ADDITIONAL_QUESTIONS];

export function LogicalReasoningTest({ onComplete }: LogicalReasoningTestProps) {
  const { t } = useLanguage();
  const [stage, setStage] = useState<'instructions' | 'test' | 'feedback' | 'results'>('instructions');
  const [currentQuestion, setCurrentQuestion] = useState(0);
  const [selectedQuestions, setSelectedQuestions] = useState<Question[]>([]);
  const [responses, setResponses] = useState<number[]>([]);
  const [timeLeft, setTimeLeft] = useState(900); // 15分钟
  const [startTime, setStartTime] = useState<number>(0);
  const [score, setScore] = useState(0);
  const [selectedAnswer, setSelectedAnswer] = useState<number | null>(null);
  const [showFeedback, setShowFeedback] = useState(false);

  const QUESTIONS_PER_TEST = 15; // 每次测试15道题

  // 随机选择题目
  const selectRandomQuestions = () => {
    const shuffled = [...ALL_QUESTIONS].sort(() => Math.random() - 0.5);
    
    // 确保每种类型都有一定数量的题目
    const questionsByType: { [key: string]: Question[] } = {
      deduction: [],
      induction: [],
      syllogism: [],
      conditional: [],
      analogy: []
    };
    
    // 按类型分组
    shuffled.forEach(q => {
      if (questionsByType[q.type].length < 3) {
        questionsByType[q.type].push(q);
      }
    });
    
    // 收集选中的题目
    const selected: Question[] = [];
    Object.values(questionsByType).forEach(typeQuestions => {
      selected.push(...typeQuestions);
    });
    
    // 如果不够15道，随机补充
    if (selected.length < QUESTIONS_PER_TEST) {
      const remaining = shuffled.filter(q => !selected.includes(q));
      const needed = QUESTIONS_PER_TEST - selected.length;
      selected.push(...remaining.slice(0, needed));
    }
    
    // 最终随机排序
    return selected.sort(() => Math.random() - 0.5).slice(0, QUESTIONS_PER_TEST);
  };

  useEffect(() => {
    let interval: NodeJS.Timeout;
    if (stage === 'test' && timeLeft > 0) {
      interval = setInterval(() => {
        setTimeLeft(prev => {
          if (prev <= 1) {
            setStage('results');
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
    }
    return () => clearInterval(interval);
  }, [stage, timeLeft]);

  const handleStartTest = () => {
    const questions = selectRandomQuestions();
    setSelectedQuestions(questions);
    setStage('test');
    setStartTime(Date.now());
  };

  const handleAnswer = (answerIndex: number) => {
    setSelectedAnswer(answerIndex);
    setShowFeedback(true);
    
    const correct = answerIndex === selectedQuestions[currentQuestion].correct;
    
    setResponses(prev => [...prev, answerIndex]);
    
    if (correct) {
      setScore(prev => prev + 1);
    }

    // 延迟2.5秒后进入下一题或结束测试
    setTimeout(() => {
      setShowFeedback(false);
      setSelectedAnswer(null);
      
      if (currentQuestion < selectedQuestions.length - 1) {
        setCurrentQuestion(prev => prev + 1);
      } else {
        setStage('results');
      }
    }, 2500);
  };

  const handleComplete = () => {
    const totalQuestions = selectedQuestions.length;
    const correctAnswers = score;
    const accuracy = Math.round((correctAnswers / totalQuestions) * 100);
    const timeUsed = Math.round((Date.now() - startTime) / 1000);

    // 按题目类型统计
    const typeStats: { [key: string]: { correct: number; total: number } } = {
      deduction: { correct: 0, total: 0 },
      induction: { correct: 0, total: 0 },
      syllogism: { correct: 0, total: 0 },
      conditional: { correct: 0, total: 0 },
      analogy: { correct: 0, total: 0 }
    };

    selectedQuestions.forEach((question, index) => {
      const type = question.type;
      typeStats[type].total++;
      if (responses[index] === question.correct) {
        typeStats[type].correct++;
      }
    });

    const result: TestResult = {
      id: Date.now().toString(),
      testType: 'logical',
      score: accuracy,
      completedAt: new Date(),
      duration: timeUsed,
      details: {
        totalQuestions,
        correctAnswers,
        accuracy,
        typeBreakdown: Object.entries(typeStats).map(([type, stats]) => ({
          type,
          accuracy: stats.total > 0 ? Math.round((stats.correct / stats.total) * 100) : 0,
          correct: stats.correct,
          total: stats.total
        })),
        averageTimePerQuestion: Math.round(timeUsed / totalQuestions),
        questionsUsed: selectedQuestions.map(q => q.id) // 记录使用了哪些题目
      }
    };

    onComplete(result);
  };

  if (stage === 'instructions') {
    return (
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="max-w-2xl mx-auto"
      >
        <Card className="bg-white/90 backdrop-blur-sm border-purple-200 shadow-lg">
          <CardHeader className="text-center pb-8">
            <div className="w-16 h-16 bg-gradient-to-br from-purple-600 to-indigo-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg">
              <Puzzle className="w-8 h-8 text-white" />
            </div>
            <CardTitle className="text-2xl text-slate-800">逻辑推理测试</CardTitle>
            <p className="text-slate-600 mt-2">测试您的逻辑思维和推理能力</p>
          </CardHeader>
          
          <CardContent className="space-y-6">
            <div className="bg-gradient-to-r from-purple-50 to-indigo-50 rounded-xl p-6 border border-purple-100">
              <h3 className="font-semibold text-purple-900 mb-4 flex items-center gap-2">
                <Star className="w-5 h-5" />
                测试说明
              </h3>
              <div className="space-y-3 text-slate-700">
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-purple-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">1</span>
                  <p>本测试包含15道逻辑推理题，每次随机选择</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-purple-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">2</span>
                  <p>涵盖演绎推理、归纳推理、类比推理等多种题型</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-purple-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">3</span>
                  <p>仔细阅读题目，选择最符合逻辑的答案</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-purple-600 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">4</span>
                  <p>时间限制15分钟，建议平均每题1分钟</p>
                </div>
              </div>
            </div>

            <div className="grid md:grid-cols-2 gap-4">
              <div className="bg-gradient-to-br from-blue-50 to-blue-100 rounded-xl p-4 border border-blue-200">
                <h4 className="font-semibold text-blue-800 mb-2">演绎推理</h4>
                <p className="text-sm text-blue-700">从一般到特殊的推理</p>
              </div>
              <div className="bg-gradient-to-br from-green-50 to-green-100 rounded-xl p-4 border border-green-200">
                <h4 className="font-semibold text-green-800 mb-2">归纳推理</h4>
                <p className="text-sm text-green-700">从特殊到一般的推理</p>
              </div>
            </div>

            <div className="grid md:grid-cols-3 gap-4">
              <div className="text-center p-4 bg-gradient-to-br from-purple-50 to-purple-100 rounded-xl border border-purple-200">
                <div className="text-2xl font-bold text-purple-600 mb-1">40+</div>
                <div className="text-sm text-purple-700">题库数量</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-indigo-50 to-indigo-100 rounded-xl border border-indigo-200">
                <div className="text-2xl font-bold text-indigo-600 mb-1">15</div>
                <div className="text-sm text-indigo-700">本次题目</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-purple-50 to-indigo-50 rounded-xl border border-purple-200">
                <div className="text-2xl font-bold text-slate-600 mb-1">15</div>
                <div className="text-sm text-slate-700">分钟限时</div>
              </div>
            </div>

            <Button 
              onClick={handleStartTest}
              className="w-full bg-gradient-to-r from-purple-600 to-indigo-500 hover:from-purple-700 hover:to-indigo-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
              size="lg"
            >
              开始测试
            </Button>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  if (stage === 'test' && selectedQuestions.length > 0) {
    const question = selectedQuestions[currentQuestion];
    const progress = ((currentQuestion) / selectedQuestions.length) * 100;

    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="max-w-4xl mx-auto space-y-6"
      >
        {/* 顶部状态栏 */}
        <div className="flex flex-col sm:flex-row gap-4 items-center justify-between">
          <div className="flex items-center gap-4">
            <Badge variant="outline" className="bg-purple-100 text-purple-700 border-purple-300">
              题目 {currentQuestion + 1} / {selectedQuestions.length}
            </Badge>
            <Badge variant="outline" className={`
              ${question.type === 'deduction' ? 'bg-blue-100 text-blue-700 border-blue-300' :
                question.type === 'induction' ? 'bg-green-100 text-green-700 border-green-300' :
                question.type === 'syllogism' ? 'bg-yellow-100 text-yellow-700 border-yellow-300' :
                question.type === 'conditional' ? 'bg-red-100 text-red-700 border-red-300' :
                'bg-orange-100 text-orange-700 border-orange-300'}
            `}>
              {question.type === 'deduction' ? '演绎推理' :
               question.type === 'induction' ? '归纳推理' :
               question.type === 'syllogism' ? '三段论' :
               question.type === 'conditional' ? '条件推理' : '类比推理'}
            </Badge>
            <Badge variant="outline" className={`
              ${question.difficulty === 'easy' ? 'bg-green-100 text-green-700 border-green-300' :
                question.difficulty === 'medium' ? 'bg-yellow-100 text-yellow-700 border-yellow-300' :
                'bg-red-100 text-red-700 border-red-300'}
            `}>
              {question.difficulty === 'easy' ? '简单' :
               question.difficulty === 'medium' ? '中等' : '困难'}
            </Badge>
            <div className="flex items-center gap-2 text-slate-600">
              <Trophy className="w-4 h-4" />
              <span className="font-semibold">{score}</span>
            </div>
          </div>
          
          <div className="flex items-center gap-2">
            <Clock className="w-4 h-4 text-slate-500" />
            <span className={`font-mono text-lg font-bold ${timeLeft <= 60 ? 'text-red-500' : 'text-slate-700'}`}>
              {Math.floor(timeLeft / 60)}:{(timeLeft % 60).toString().padStart(2, '0')}
            </span>
          </div>
        </div>

        <Progress value={progress} className="h-2" />

        {/* 问题区域 */}
        <Card className="bg-white/90 backdrop-blur-sm border-purple-200 shadow-lg">
          <CardHeader>
            <CardTitle className="text-xl text-slate-800">{question.question}</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            {question.options.map((option, index) => {
              const isSelected = selectedAnswer === index;
              const isCorrect = index === question.correct;
              const isAnswered = selectedAnswer !== null;
              
              return (
                <motion.div
                  key={index}
                  whileHover={!isAnswered ? { scale: 1.01 } : {}}
                  whileTap={!isAnswered ? { scale: 0.99 } : {}}
                >
                  <Button
                    variant="outline"
                    onClick={() => !isAnswered && handleAnswer(index)}
                    disabled={isAnswered}
                    className={`w-full h-auto min-h-[3rem] text-left justify-start p-4 transition-all duration-300 ${
                      isAnswered
                        ? isSelected
                          ? isCorrect
                            ? 'bg-green-50 border-green-300 text-green-800'
                            : 'bg-red-50 border-red-300 text-red-800'
                          : isCorrect
                            ? 'bg-green-50 border-green-300 text-green-800'
                            : 'bg-gray-100 border-gray-300 text-gray-600'
                        : 'hover:bg-purple-50 hover:border-purple-300'
                    }`}
                  >
                    <div className="flex items-center gap-3 w-full">
                      <span className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 ${
                        isAnswered
                          ? isSelected
                            ? isCorrect
                              ? 'bg-green-500 text-white'
                              : 'bg-red-500 text-white'
                            : isCorrect
                              ? 'bg-green-500 text-white'
                              : 'bg-gray-300 text-gray-600'
                          : 'bg-purple-100 text-purple-700'
                      }`}>
                        {isAnswered && isSelected && !isCorrect && (
                          <XCircle className="w-5 h-5" />
                        )}
                        {isAnswered && isCorrect && (
                          <CheckCircle className="w-5 h-5" />
                        )}
                        {!isAnswered && String.fromCharCode(65 + index)}
                        {isAnswered && !isSelected && !isCorrect && String.fromCharCode(65 + index)}
                      </span>
                      <span className="flex-1">{option}</span>
                      {isAnswered && isSelected && (
                        <div className="flex items-center gap-1">
                          {isCorrect ? (
                            <Badge className="bg-green-100 text-green-700 border-green-300">
                              正确
                            </Badge>
                          ) : (
                            <Badge className="bg-red-100 text-red-700 border-red-300">
                              错误
                            </Badge>
                          )}
                        </div>
                      )}
                    </div>
                  </Button>
                </motion.div>
              );
            })}
            
            {/* 答题反馈区域 */}
            <AnimatePresence>
              {showFeedback && selectedAnswer !== null && (
                <motion.div
                  initial={{ opacity: 0, y: 20, height: 0 }}
                  animate={{ opacity: 1, y: 0, height: 'auto' }}
                  exit={{ opacity: 0, y: -20, height: 0 }}
                  transition={{ duration: 0.3 }}
                  className="mt-6 p-4 rounded-xl border overflow-hidden"
                  style={{
                    backgroundColor: selectedAnswer === question.correct ? '#f0fdf4' : '#fef2f2',
                    borderColor: selectedAnswer === question.correct ? '#bbf7d0' : '#fecaca'
                  }}
                >
                  <div className="flex items-start gap-3">
                    <div className={`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ${
                      selectedAnswer === question.correct ? 'bg-green-500' : 'bg-red-500'
                    }`}>
                      {selectedAnswer === question.correct ? (
                        <CheckCircle className="w-5 h-5 text-white" />
                      ) : (
                        <XCircle className="w-5 h-5 text-white" />
                      )}
                    </div>
                    <div className="flex-1">
                      <div className={`font-semibold mb-2 ${
                        selectedAnswer === question.correct ? 'text-green-800' : 'text-red-800'
                      }`}>
                        {selectedAnswer === question.correct ? '回答正确！' : '回答错误'}
                      </div>
                      {selectedAnswer !== question.correct && (
                        <div className="mb-2 text-sm text-red-700">
                          正确答案是：<span className="font-semibold">
                            {String.fromCharCode(65 + question.correct)}. {question.options[question.correct]}
                          </span>
                        </div>
                      )}
                      <div className="flex items-start gap-2">
                        <Lightbulb className={`w-4 h-4 mt-0.5 flex-shrink-0 ${
                          selectedAnswer === question.correct ? 'text-green-600' : 'text-red-600'
                        }`} />
                        <span className={`text-sm ${
                          selectedAnswer === question.correct ? 'text-green-700' : 'text-red-700'
                        }`}>
                          {question.explanation}
                        </span>
                      </div>
                    </div>
                  </div>
                </motion.div>
              )}
            </AnimatePresence>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  if (stage === 'results') {
    const totalQuestions = selectedQuestions.length;
    const correctAnswers = score;
    const accuracy = Math.round((correctAnswers / totalQuestions) * 100);

    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="max-w-2xl mx-auto"
      >
        <Card className="bg-white/90 backdrop-blur-sm border-purple-200 shadow-xl">
          <CardHeader className="text-center pb-6">
            <motion.div
              initial={{ scale: 0 }}
              animate={{ scale: 1 }}
              transition={{ delay: 0.2, type: "spring", stiffness: 200 }}
              className="w-20 h-20 bg-gradient-to-br from-purple-600 to-indigo-500 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg"
            >
              <Trophy className="w-10 h-10 text-white" />
            </motion.div>
            
            <CardTitle className="text-3xl text-slate-800 mb-2">测试完成！</CardTitle>
            <div className="text-6xl font-bold bg-gradient-to-r from-purple-600 to-indigo-500 bg-clip-text text-transparent">
              {accuracy}
            </div>
            <p className="text-slate-600">逻辑推理准确率</p>
          </CardHeader>
          
          <CardContent className="space-y-6">
            <div className="grid grid-cols-2 gap-4">
              <div className="text-center p-4 bg-gradient-to-br from-purple-50 to-purple-100 rounded-xl border border-purple-200">
                <div className="text-2xl font-bold text-purple-600 mb-1">{correctAnswers}/{totalQuestions}</div>
                <div className="text-sm text-purple-700">正确题数</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-indigo-50 to-indigo-100 rounded-xl border border-indigo-200">
                <div className="text-2xl font-bold text-indigo-600 mb-1">{Math.round((Date.now() - startTime) / 60000)}分钟</div>
                <div className="text-sm text-indigo-700">用时</div>
              </div>
            </div>

            <Button 
              onClick={handleComplete}
              className="w-full bg-gradient-to-r from-purple-600 to-indigo-500 hover:from-purple-700 hover:to-indigo-600 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
              size="lg"
            >
              查看详细结果
            </Button>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  return null;
}